package org.example.ims.Controller.Base;

import org.example.ims.DTO.Response;
import org.example.ims.Entity.Base.Product;
import org.example.ims.Service.Base.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    // 根据ID查询商品类别
    @GetMapping("/{id}")
    public ResponseEntity<Response<Product>> getProductById(@PathVariable Integer id) {
        return productService.findProductById(id)
                .map(product -> ResponseEntity.ok(Response.success(product)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Response.<Product>error("NOT_FOUND", "商品类别（ID：" + id + "）未找到")));
    }

    // 查询所有商品类别
    @GetMapping("/search")
    public Response<Page<Product>> getAllProducts(@RequestParam(defaultValue = "0") Integer page,
                                        @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(productService.findAllProducts(page,size));
    }

    // 自定义查询商品
    @GetMapping
    public Response<Page<Product>> searchProducts(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String status,
            @RequestParam int page,
            @RequestParam int size) {
        return Response.success(productService.searchProducts(name, categoryId, status, page, size));
    }


    // 创建商品类别
    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        Product savedProduct = productService.addProduct(product);
        return ResponseEntity.ok(savedProduct);
    }

    // 更新商品类别
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Integer id, @RequestBody Product productDetails) {
        Product updatedProduct = productService.updateProduct(id, productDetails);
        return ResponseEntity.ok(updatedProduct);
    }

    // 删除商品类别
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Integer id) {
        productService.deleteProductById(id);
        return ResponseEntity.ok().build();
    }
}